package com.sczmgk.hotline.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.ClipboardManager;
import android.text.Spannable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.callback.MsgCallback;
import com.hyphenate.easeui.callback.OnVoiceClickListener;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.utils.MyLog;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.iflytek.cloud.SpeechRecognizer;
import com.sczmgk.frame.http.Tools;
import com.sczmgk.hotline.MyApp;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.base.ChatBaseActivity;
import com.sczmgk.hotline.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.db.impl.ChatMsgDaoImpl;
import com.sczmgk.hotline.db.impl.UserDaoImpl;
import com.sczmgk.hotline.dialog.DialogFactory;
import com.sczmgk.hotline.dialog.MessageDialog;
import com.sczmgk.hotline.entity.ChatMsgBean;
import com.sczmgk.hotline.entity.EMMMessageComparator;
import com.sczmgk.hotline.entity.XiaoiMsgBean;
import com.sczmgk.hotline.entity.newentity.ChatMessageComparator;
import com.sczmgk.hotline.httpUtils.MyHttp;
import com.sczmgk.hotline.msc.MscUtils;
import com.sczmgk.hotline.utils.CacheUtils;
import com.sczmgk.hotline.utils.CommonUtils;
import com.sczmgk.hotline.utils.HxUtils;
import com.sczmgk.hotline.utils.MyToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sczmgk.hotline.MyApp.loginUserUid;
import static com.sczmgk.hotline.utils.CacheUtils.getLoginStatus;

public class ChatActivity extends ChatBaseActivity<ChatMsgBean> {
    private static final int SET_ICON = 103;
//    private static final int TIMER = 1;
    private SpeechRecognizer mIat;
    /**
     * 音量提示的窗口
     */
    private LinearLayout mVoiceHintWindow;
    private int tempsize = 0;
    /**
     * 音量大小的图片
     */
    private ImageView mVolume;
    protected static final int SET_CONTECT = 2;
    private static final int CHANGE_VOLUME = 3;
    private boolean isAndroid;
    private final String TAG = ChatActivity.class.getSimpleName();
    private EaseChatFragment chatFragment = null;
    private final int SET_ESAEUI_MSG_REFRESH = 1000;
    private final int SET_ESAEUI_MSG_REFRESH_LAST_POSITION = 1002;
    private final int SET_ESAEUI_MSG_REFRESH_SEEK_TO = 1003;
    private EMMMessageComparator comparator = new EMMMessageComparator();
    private ChatMessageComparator chatMessageComparator = new ChatMessageComparator();
    private ImageView buttonSetModeVoice;
    private EditText inputView;
    private MsgCount msgCount;

    List<EMMessage> emMessages;

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        switch (msg.what) {

            case REFRESH_LIST://服务器拉取的数据
                MyLog.d(TAG, "刷新数据");
                if (tempsize == 0) {

                    firstLoadMsg();
                } else {
                    loadMoreMsg();
                }
                break;
            case SET_ESAEUI_MSG_REFRESH_LAST_POSITION:
                MyLog.d(TAG, "第一次加载或，接收，发送消息，显示到最后一条数据");
                emMessages = (List<EMMessage>) msg.obj;
                Collections.sort(emMessages, comparator);
                chatFragment.setChatMessagesRefreshLastSelection(getEMMessageArray(emMessages));
                break;
            case SET_ESAEUI_MSG_REFRESH:
                MyLog.d(TAG, "仅刷新界面");
                emMessages = (List<EMMessage>) msg.obj;
                Collections.sort(emMessages, comparator);
                chatFragment.setChatMessagesRefresh(getEMMessageArray(emMessages));
                break;
            case SET_ESAEUI_MSG_REFRESH_SEEK_TO:
                emMessages = (List<EMMessage>) msg.obj;
                int position = msg.arg1;
                MyLog.d(TAG, "加载更多，显示的位置：" + position);
                Collections.sort(emMessages, comparator);
                chatFragment.setChatMessagesRefreshSeekTo(getEMMessageArray(emMessages), position);
                break;
            case SET_CONTECT:
                String content = (String) msg.obj;
                //TODO 语音设置给输入控件
                inputView.setText(content);
                break;
            case CHANGE_VOLUME:
                int volume = (Integer) msg.obj;

                if (volume > 35) {
                    mVolume.setImageResource(R.drawable.ic_volume_07);
                } else if (volume > 30) {
                    mVolume.setImageResource(R.drawable.ic_volume_06);
                } else if (volume > 25) {
                    mVolume.setImageResource(R.drawable.ic_volume_05);
                } else if (volume > 20) {
                    mVolume.setImageResource(R.drawable.ic_volume_04);
                } else if (volume > 15) {
                    mVolume.setImageResource(R.drawable.ic_volume_03);
                } else if (volume > 10) {
                    mVolume.setImageResource(R.drawable.ic_volume_02);
                } else if (volume > 5) {
                    mVolume.setImageResource(R.drawable.ic_volume_01);
                }
//    			mVolume.setImageResource(R.drawable.ic_volume_01);
                break;
            case SET_ICON:
//                if (buttonSetModeVoice == null) {
//                    buttonSetModeVoice = (ImageView) chatFragment.getButtonSetModeVoice();
//                    buttonSetModeVoice.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            switchOnline();
//                        }
//                    });
//                    setOnlineBtnBackground();
//                }


                break;
//            case TIMER:
//                if (!isAndroid) {
//                    MyLog.d(TAG, "输入超时，切换机器人");
//                    setAndroid();
//                }
//                endTimer();
//                break;
        }
    }


    /**
     * 网络加载消息
     */
    private void firstLoadMsg() {

        //更新数据库
        //1.第一次更新全部数据
        //2.加载更多时更新加载的数据
        //3.加载更多数据的计算
        // a.加载前记住当前数据的数量
        insertOrUpdateDB(lists, new OnOperationDbCallback() {
            @Override
            public void onSuccess() {

                //刷新界面
                getMsgFormDB(new OnLoadDbCallback() {
                    @Override
                    public void onLoadSuccess(List<EMMessage> emMessages) {
                        setEaseUIChatMessageRefreshLastSelection(emMessages);
                    }
                });
                int size = lists.size();
                tempsize = size;

            }
        });


    }

    /**
     * 网络加载消息
     */
    private void loadMoreMsg() {

        //更新数据库
        //1.第一次更新全部数据
        //2.加载更多时更新加载的数据
        //3.加载更多数据的计算
        // a.加载前记住当前数据的数量
        insertOrUpdateDB(lists, new OnOperationDbCallback() {
            @Override
            public void onSuccess() {

                //取得要展示的位置
                final int currentPosition = tempsize;
                //刷新界面
                getMsgFormDB(new OnLoadDbCallback() {
                    @Override
                    public void onLoadSuccess(List<EMMessage> emMessages) {
                        //当前展示的的消息位置 lists 总数 与新加载条数之差
                        setEaseUIChatMessageRefreshSeekTo(emMessages, emMessages.size() - currentPosition);
                    }
                });

                int size = lists.size();
                tempsize = size;

            }
        });

    }

    @Override
    public Map<String, Object> getRequestData(int page, String keyword) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", loginUserUid);
        maps.put("pageindex", page);
        maps.put("imei", MyApp.imei);
        return maps;
    }

    @Override
    public String getRquestUrl() {
        return Constant.BASE_URL + Constant.GET_CHATLIST;
    }

    @Override
    public String getCacheKey() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        setRightBtnVisibility(View.VISIBLE);
        isAndroid = getIntent().getBooleanExtra("isAndroid",false);

        //设置用户头像
        if (getLoginStatus(ChatActivity.this) && UserDaoImpl.getLoginUser(this) != null) {
            EaseUserUtils.userIconPath = (UserDaoImpl.getLoginUser(this).imageLocalPath);
        } else {
            EaseUserUtils.userIconPath = "";
        }
        setRightBtnText(R.string.hot_line);
        msgCount = new MsgCount();
        setRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPhone(ChatActivity.this.getResources().getString(R.string.hot_line));
            }
        });
//        isAndroid = MainActivity.msgTimerService.isAndroid();
//        if (!isAndroid) {
//            startTimer();
//        }
        MyApp.IS_CHAT_PROGUND = true;
        if (isAndroid) {
            setTitle("机器人");
        } else {
            setTitle("人工在线");
        }
        chatFragment = new EaseChatFragment(new MsgCallback() {
            @Override
            public void onSend(EMMessage message) {
                //TODO 发送消息
                addNewMsg(message);


            }

            @Override
            public void onSendStatusChanged(EMMessage message) {
                //TODO　更新消息状态
                updataMsg(message);
            }

            @Override
            public void onReciver(EMMessage message) {
                //TODO 接收到消息，存入数据库，上传服务器
                //1. 存缓存
                //2. 上传服务器
                //3. 刷新界面
                reciverHxNewMsg(message);

            }

            @Override
            public void onRefresh() {

                MyLog.i(TAG, "下拉刷新");
            }

            @Override
            public void onLoadMore() {

                tempsize = lists.size();
                MyLog.d(TAG, "加载更多,当前lists size: " + tempsize);
                if (getLoginStatus(ChatActivity.this)) {
                    loadMore();//已登录,网络请求数据
                } else {
                    //未登录,取本地数据
                    //
                }


            }

            @Override
            public void onRefreshToLast() {
                MyLog.d(TAG, "刷新到最后一条数据");
            }
        }, MyApp.loginUserUid, new EaseChatFragment.InputCallback() {
            @Override
            public void onInputCallback(String msg) {

                if (!Tools.isEmpty(msg.trim())) {

//                    //TODO
//                    //1.人工在线
//                    boolean isSwitch = msgCount.addMsg(msg, isAndroid);
//                    if (isSwitch) {
//                        MyLog.e(TAG, "已连续问了三次同样的问题,切换机器人，发消息给机器人");
//                        setAndroid();
//                    }
//                    if (!isAndroid) {
//
//                        startTimer();
//                    }

                    chatFragment.sendTextMessage(msg);
                } else {
                    MyToast.showDebug(ChatActivity.this, "请输入内容");
                }

            }
        });

        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.fl_chat_container, chatFragment).commit();
        chatFragment.setChatFragmentListener(new EaseChatFragment.EaseChatFragmentHelper() {
            @Override
            public void onSetMessageAttributes(EMMessage message) {

            }

            @Override
            public void onEnterToChatDetails() {

            }

            @Override
            public void onAvatarClick(String username) {

            }

            @Override
            public void onAvatarLongClick(String username) {

            }

            @Override
            public boolean onMessageBubbleClick(EMMessage message) {
                return false;
            }

            @Override
            public void onMessageBubbleLongClick(EMMessage message) {
                //TODO 废弃


            }

            @Override
            public void onMessageBubbleLongClick(EMMessage message, View v) {

                // 长按显示 复制，转发，删除按钮
                PopupWindow popupWindow = new PopupWindow(View.inflate(getApplicationContext(), R.layout.long_click_menu, null));
                popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                View view = popupWindow.getContentView();

                setItemClickStatus(popupWindow, view, R.id.long_click_copy, message);
                setItemClickStatus(popupWindow, view, R.id.long_click_convrt, message);
                setItemClickStatus(popupWindow, view, R.id.long_click_delete, message);

                // 正文控件计算x,y坐标的数组
                int headViewHeight = getResources().getDimensionPixelSize(R.dimen.pahead_view_height);
                view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                int popViewHeight = view.getMeasuredHeight();
                int popViewWidth = view.getMeasuredWidth();
                int[] location = new int[2];
                v.getLocationOnScreen(location);
                Log.i("yy", "x:" + location[0] + ",y:" + location[1] + "," + v.getWidth() + "," + popViewWidth + ","
                        + popViewHeight);
                int x = location[0] + (v.getWidth() - popViewWidth) / 2;
                int y = location[1] - popViewHeight;
                // 控件上面显示不下pop，显示在控件的下面
                if (location[1] - headViewHeight - popViewHeight <= 0) {
                    view.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_long_press_up_bg));
                    y = location[1] + v.getHeight();
                } else {
                    view.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_long_press_down_bg));
                }
                popupWindow.showAtLocation(v, Gravity.TOP | Gravity.START, x, y);
            }

            @Override
            public boolean onExtendMenuItemClick(int itemId, View view) {
                return false;
            }

            @Override
            public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
                return null;
            }

            @Override
            public void onOnlineClick() {

                //TODO 人工在线
                MyLog.i(TAG, "人工在线");

//                switchOnline();
            }

            @Override
            public void onCallPhoneClick() {
                //TODO 热线电话

                MyLog.d(TAG, "热线电话");
            }

        });
        chatFragment.setOnVoiceClickListener(new OnVoiceClickListener() {
            @Override
            public void onVoiceClick() {
                MyLog.d(TAG, "语音输入点击了");

//                    //设置语音识别
////                    buttonSetModeVoice.setClickable(true);
////                    buttonSetModeVoice.setOnTouchListener(touchListener);
//                    buttonSetModeVoice.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            MyLog.d(TAG,"机器人切换点击 事件");
//                            switchOnline();
//                        }
//                    });
//
//                if(inputView == null){
//
//                    inputView = chatFragment.getInputView();
//                }

            }
        });
        //展示数据库缓存数据
        getMsgFormDBinit(new OnLoadDbCallback() {
            @Override
            public void onLoadSuccess(List<EMMessage> emMessages) {
                setEaseUIChatMessageRefreshLastSelection(emMessages);
            }
        });
        //设置返回按钮点击事件
        setLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatFragment.onBackPressed();
            }
        });
        //1.上传未上传的消息
        //2.上传完成再加载数据
        uploadCacheMsg();

        if (getLoginStatus(ChatActivity.this)) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadData(1, "", LOAD_NORMAL);
                }
            }, 1000);
        }

        final String input = getIntent().getStringExtra("input");
        if (!Tools.isEmpty(input)) {


            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    EMMessage msg = EMMessage.createTxtSendMessage(input, "user");//创建消息
                    EaseChatFragment.setAttr(msg);
                    addNewMsg(msg);
                }
            }, 1000);

        }
        initView();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(SET_ICON);
            }
        }, 500);
        chatFragment.setAndroid(isAndroid);
    }

    /**
     * 功能点击事件
     *
     * @param v
     */
    private void onFuntionClick(View v) {

        final EMMessage emMessage = (EMMessage) v.getTag();
        if (emMessage == null) {
            return;
        }

        switch (v.getId()) {
            case R.id.long_click_convrt://转发
                //转发

                break;
            case R.id.long_click_delete:
                // TODO 删除

                MessageDialog chooseDialog = DialogFactory.chooseDialog(ChatActivity.this, "确定要删除消息", "是", "否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        ChatMsgDaoImpl.getIntance(ChatActivity.this).deleteAll();
//                        getMsgFormDB(new OnLoadDbCallback() {
//                            @Override
//                            public void onLoadSuccess(List<EMMessage> emMessages) {
//                                setEaseUIChatMessageRefreshLastSelection(emMessages);
//                            }
//                        });

                        //删除数据
                        //1.删除服务器数据
                        //2.删除DB
                        //3.刷新界面
                        final ChatMsgBean chatMsg = getChatMsg(emMessage, false);

                        Map<String, Object> dapMap = new HashMap<String, Object>();
                        dapMap.put("userid", CacheUtils.getLoginUserid(ChatActivity.this));
                        dapMap.put("chatid", chatMsg.getChatid());
                        MyHttp.request(ChatActivity.this, Constant.BASE_URL + Constant.DELETE_CHAT_MSG_URL, dapMap, MyHttp.POST, false, null, new SimplePaserJsonCallback() {
                            @Override
                            public void onVerifyIsNull() {

                                deleteMsg(chatMsg, emMessage);
                            }

                            @Override
                            public void onVerifySuccess(String dataRaw) {

                            }

                            @Override
                            public void onServerUnKnownError() {

                            }

                            @Override
                            public void onErrorCodeError(String msg) {
                                deleteMsg(chatMsg, emMessage);

                            }
                        });

                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                chooseDialog.setTitle("提示");
                chooseDialog.show();
                break;
            case R.id.long_click_copy:
//                 拷贝
                ClipboardManager clip = (ClipboardManager)getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);

                EMTextMessageBody txtBody = (EMTextMessageBody) emMessage.getBody();
                Spannable span = EaseSmileUtils.getSmiledText(ChatActivity.this, txtBody.getMessage());
                // 设置内容
                MyLog.d(TAG, "clip: " + span.toString());
                clip.setText(span.toString());
                Toast.makeText(getApplicationContext(), R.string.copy_successful, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    private void deleteMsg(ChatMsgBean chatMsg, EMMessage emMessage) {
        //TODO 服务器中不存在此务消息删除消息，并刷新界面
        if (ChatMsgDaoImpl.getIntance(ChatActivity.this).deleteMsgByChatid(chatMsg.getChatid()) > 0) {
//                                  getMsgFormDB(new OnLoadDbCallback() {
//                                      @Override
//                                      public void onLoadSuccess(List<EMMessage> emMessages) {
//                                      }
//                                  });
            //A
            //1.找到当前展示的位置
            //2.删除list对应的数据
            //3.刷新界面,并跳转到当前的位置

            //B
            //1.找到当前展示的位置
            //2.取得当前展示消息的总条数
            //3.取数据库消息
            //4.刷新界面,并跳转到当前的位置

            int position = 0;
            for (int i = 0; i < emMessages.size(); i++) {

                String chatid = emMessages.get(i).getStringAttribute(ChatMsgBean.ATTR_KEY_CHATID, "");
                String chatid1 = emMessage.getStringAttribute(ChatMsgBean.ATTR_KEY_CHATID, "");
                if (!Tools.isEmpty(chatid) && !Tools.isEmpty(chatid1)) {
                    if (chatid.equals(chatid1)) {//找到删除消息的角标
                        position = i;
                        break;
                    }
                }
            }
            int totalCount = lists.size();
            tempsize = totalCount;

            final int finalPosition = position;

            getMsgFormDB(new OnLoadDbCallback() {
                @Override
                public void onLoadSuccess(List<EMMessage> emMessages) {
                    setEaseUIChatMessageRefreshSeekTo(emMessages, finalPosition);
                }
            });
        }
    }

    /**
     * 设置条目点击事件
     *
     * @param popupWindow
     * @param view
     * @param resId
     * @param message
     */
    private void setItemClickStatus(final PopupWindow popupWindow, View view, int resId, EMMessage message) {
        View v = view.findViewById(resId);
        if (v != null) {
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onFuntionClick(v);
                    popupWindow.dismiss();
                }
            });
            v.setTag(message);
        }
    }

//    private void switchOnline() {
//        if (isAndroid) {
//            MainActivity.msgTimerService.cancelTimer();
//            isAndroid = !isAndroid;
//            setTitle("人工在线");
//            chatFragment.setAndroid(isAndroid);
//            //2.设置最后一条消息的attr
//            clearHintTag();
//            Collections.sort(lists, chatMessageComparator);
//            if (lists.size() > 1) {
//                ChatMsgBean chatMsgBean = lists.get(lists.size() - 1);
//                chatMsgBean.setShowHint(ChatMsgBean.ATTR_VALUE_HINT_SHOW);
//                chatMsgBean.setHintType(ChatMsgBean.ATTR_VALUE_HINT_TYPE_ONLINE);
//                //刷新界面
//                setEaseUIChatMessageRefresh();
//            }
//
//
//            //TODO 开定时器
//            startTimer();
//        } else {
//            setTitle("机器人");
//            isAndroid = !isAndroid;
//            chatFragment.setAndroid(isAndroid);
//            clearHintTag();
//            Collections.sort(lists, chatMessageComparator);
//            if (lists.size() > 1) {
//                ChatMsgBean chatMsgBean = lists.get(lists.size() - 1);
//                chatMsgBean.setShowHint(ChatMsgBean.ATTR_VALUE_HINT_SHOW);
//                chatMsgBean.setHintType(ChatMsgBean.ATTR_VALUE_HINT_TYPE_ANDROID);
//                //刷新界面
//                setEaseUIChatMessageRefresh();
//            }
//
//            endTimer();
//        }
//        setOnlineBtnBackground();
//    }

//    private void endTimer() {
//        mHandler.removeCallbacks(timerRunnable);
//    }

//    private Runnable timerRunnable = new Runnable() {
//        @Override
//        public void run() {
//            mHandler.sendEmptyMessage(TIMER);
//        }
//    };

//    private void startTimer() {
//        MyLog.i(TAG, "开始计时");
//        endTimer();
//
//        mHandler.postDelayed(timerRunnable, Constant.DELAY_TIME);
//    }

//    private void setAndroid() {
//        MainActivity.msgTimerService.cancelTimer();
//        isAndroid = true;
//        setTitle("机器人");
//        chatFragment.setAndroid(isAndroid);
//        clearHintTag();
//        Collections.sort(lists, chatMessageComparator);
//        if (lists.size() > 0) {
//            ChatMsgBean chatMsgBean = lists.get(lists.size() - 1);
//            chatMsgBean.setShowHint(ChatMsgBean.ATTR_VALUE_HINT_SHOW);
//            chatMsgBean.setHintType(ChatMsgBean.ATTR_VALUE_HINT_TYPE_ANDROID);
//        }
//
//        //刷新界面
//        setEaseUIChatMessageRefresh();
//
//        setOnlineBtnBackground();
//    }

    private void setOnlineBtnBackground() {
        if (isAndroid) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chat_online);
            buttonSetModeVoice.setImageBitmap(bitmap);
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chat_android);
            buttonSetModeVoice.setImageBitmap(bitmap);
        }


    }

    /**
     * 初始化语音输入按钮
     */
    private void initView() {
        Button setResult = (Button) findViewById(R.id.bt_setresult);
        setResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("isAndroid", isAndroid);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        setLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("isAndroid", isAndroid);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        mVoiceHintWindow = (LinearLayout) findViewById(R.id.ll_voice_hint_window);
        mVoiceHintWindow.setVisibility(View.INVISIBLE);
        mVolume = (ImageView) findViewById(R.id.iv_voide_volume);
    }


    /**
     * 清除消息下面的提示（小乐为你服务）
     */
    private void clearHintTag() {
        for (ChatMsgBean list : lists) {
            // TODO 若只展示最后一条消息下面的提示（如：小乐为你服务）则放开下面注释
//            list.setShowHint(ChatMsgBean.ATTR_VALUE_HINT_HIDE);

        }
    }

    public void login(final String account, final String pwd, final String online) {
        EMClient.getInstance().login(account, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                MyLog.d(TAG, "登录成功");
                Bundle bundle = new Bundle();
                bundle.putString(EaseConstant.EXTRA_USER_ID, online);
                bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                chatFragment.setArguments(getIntent().getExtras());

            }

            @Override
            public void onError(int i, String s) {
                MessageDialog dialog = DialogFactory.chooseDialog(ChatActivity.this, "登录失败,请重试,如选择取消则不会发起人工在线咨询", "确定", "取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        login(account, pwd, online);
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                MyLog.e(TAG, "登录失败");
                dialog.setTitle("提示");
                dialog.show();
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    /**
     * @param message
     */
    private void reciverHxNewMsg(final EMMessage message) {
        //TODO 发送消息到服务器
        lists.add(HxUtils.createMyMsg(message, true));
        new Thread(new Runnable() {
            @Override
            public void run() {
                insertOrUpdateDB(message, true, new OnOperationDbCallback() {
                    @Override
                    public void onSuccess() {
                        setMsgByAddNewMsg();

                    }
                });
            }
        }).start();

    }

    /**
     * 1.消息列表增加一条数据
     * 2.存入数据库
     * 3.向服务器发送消息
     * 4.刷新界面
     *
     * @param message
     */
    private void addNewMsg(final EMMessage message) {
        //TODO 发送消息到服务器
        lists.add(HxUtils.createMyMsg(message, true));//用于展示，不需要设置需要上传标记
        new Thread(new Runnable() {
            @Override
            public void run() {

                //1.发送给小i
                //2.发送给环信
                int sendTo = message.getIntAttribute(ChatMsgBean.ATTR_KEY_SEND_TO, ChatMsgBean.ATTR_VALUE_ANDROID);
                //TODO 如果发送给小i消息需要批量上传将下面变量设置成true,
                boolean needUpload ;
                if (sendTo == ChatMsgBean.ATTR_VALUE_ONLINE) {
                    needUpload = true;
                }else{
                    needUpload = false;
                }

                insertOrUpdateDB(message, needUpload, new OnOperationDbCallback() {
                    @Override
                    public void onSuccess() {
                        setMsgByAddNewMsg();
                        if (isAndroid) {
                            sendMsgToXiaoi(getChatMsg(message, true));
                        }
                    }
                });
            }
        }).start();


    }

    /**
     * 取得待上传的消息
     */
    private List<ChatMsgBean> getUpladDB() {
        List<ChatMsgBean> waitUploadList = ChatMsgDaoImpl.getIntance(ChatActivity.this).getWaitUploadList(MyApp.loginUserUid);
        return waitUploadList;
    }

    /**
     * 1.消息列表增加一条数据
     * 2.刷新界面
     * 3.存入数据库
     *
     * @param myMsg
     */
    private void receiveXiaoiNewMsg(final ChatMsgBean myMsg) {
        //TODO 发送消息到服务器
        lists.add(myMsg);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //TODO 如果小i回复消息需要批量上传，则用下面设置
//                myMsg.setDuration(ChatMsgBean.NEED_UPLOAD);
                insertOrUpdateDB(myMsg, new OnOperationDbCallback() {
                    @Override
                    public void onSuccess() {
                        setMsgByAddNewMsg();

                    }

                });
            }
        }).start();


    }

    /**
     * 更新消息
     * 1.更新数据库
     * 2.更新服务器数据
     * 3.刷新界面
     *
     * @param message
     */
    private void updataMsg(final EMMessage message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                insertOrUpdateDB(message, true, new OnOperationDbCallback() {
                    @Override
                    public void onSuccess() {
                        getMsgFormDB(new OnLoadDbCallback() {
                            @Override
                            public void onLoadSuccess(List<EMMessage> emMessages) {
                                // TODO 单刷新,不改变位置
                                setEaseUIChatMessageRefreshLastSelection(emMessages);
                            }
                        });
                    }
                });
            }
        }).start();

        //TODO 加入待上传数据库
    }

    /**
     * 取数据库消息
     */
    private void getMsgFormDB(final OnLoadDbCallback onLoadDbCallback) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                lists = ChatMsgDaoImpl.getIntance(ChatActivity.this).findByLimit(MyApp.loginUserUid, 0, tempsize,isAndroid ? ChatMsgBean.ATTR_VALUE_ANDROID:ChatMsgBean.ATTR_VALUE_ONLINE);
                //排序
                MyLog.d(TAG, "取数据库,limit: " + 0 + " offst: " + tempsize);
                if (lists != null) {
                    List<EMMessage> emMessages = getEMMessages(lists);
                    // 3. 转成环信数据对象
                    // 4. 设置展示数据
                    if (onLoadDbCallback != null) {
                        onLoadDbCallback.onLoadSuccess(emMessages);
                    }

                }
            }
        }).start();


    }

    /**
     * 取数据库消息
     */
    private void getMsgFormDBinit(final OnLoadDbCallback onLoadDbCallback) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!getLoginStatus(ChatActivity.this)) {//没有登录通过imei取得消息
                    lists = ChatMsgDaoImpl.getIntance(ChatActivity.this).findByLimitForImei(MyApp.imei, 0, 500,isAndroid ? ChatMsgBean.ATTR_VALUE_ANDROID:ChatMsgBean.ATTR_VALUE_ONLINE);
                } else {
                    lists = ChatMsgDaoImpl.getIntance(ChatActivity.this).findByLimit(MyApp.loginUserUid, 0, 10,isAndroid ? ChatMsgBean.ATTR_VALUE_ANDROID:ChatMsgBean.ATTR_VALUE_ONLINE);
                    //排序
                }

                if (lists != null) {
                    List<EMMessage> emMessages = getEMMessages(lists);
                    // 3. 转成环信数据对象
                    // 4. 设置展示数据
                    if (onLoadDbCallback != null) {
                        onLoadDbCallback.onLoadSuccess(emMessages);
                    }

                }
            }
        }).start();


    }


    @Override
    public void onSelectedPhonePermission(String phoneNumber) {

        CommonUtils.callPhone(ChatActivity.this, phoneNumber);
    }

    @Override
    public void onSelectedStroage(int position) {

    }

    @Override
    public void onSelectCamera(int position) {

    }

    /**
     * 加载本地数据库完成的回调
     */
    public interface OnLoadDbCallback {
        void onLoadSuccess(List<EMMessage> emMessages);
    }

    /**
     * 发消息刷新界面（显示到最后一条）
     *
     * @param emMessages
     */
    private void setEaseUIChatMessageRefreshLastSelection(List<EMMessage> emMessages) {
        Message msg = Message.obtain();
        msg.what = SET_ESAEUI_MSG_REFRESH_LAST_POSITION;
        msg.obj = emMessages;
        mHandler.sendMessage(msg);
    }

    /**
     * 发消息刷新界面(仅刷新)
     *
     * @param emMessages
     */
    private void setEaseUIChatMessageRefresh(List<EMMessage> emMessages) {
        Message msg = Message.obtain();
        msg.what = SET_ESAEUI_MSG_REFRESH;
        msg.obj = emMessages;
        mHandler.sendMessage(msg);
    }

    /**
     * 发消息刷新界面（仅刷新）
     */
    private void setEaseUIChatMessageRefresh() {
        Message msg = Message.obtain();
        msg.what = SET_ESAEUI_MSG_REFRESH;
        List<EMMessage> emMessages = getEMMessages(lists);
        msg.obj = emMessages;
        mHandler.sendMessage(msg);
    }

    /**
     * 发消息刷新界面（显示到指定的位置）
     *
     * @param emMessages
     * @param position
     */
    private void setEaseUIChatMessageRefreshSeekTo(List<EMMessage> emMessages, int position) {
        Message msg = Message.obtain();
        msg.what = SET_ESAEUI_MSG_REFRESH_SEEK_TO;
        msg.obj = emMessages;
        msg.arg1 = position;
        mHandler.sendMessage(msg);
    }

    /**
     * 1.tempsize ++
     * 2.给easeUIlistView加入数据
     */
    private void setMsgByAddNewMsg() {
        tempsize++;
        MyLog.d(TAG, "增加了一条消息,当前lists size: " + tempsize);
        List<EMMessage> emMessages = getEMMessages(lists);
        // 3. 转成环信数据对象
        // 4. 设置展示数据
        setEaseUIChatMessageRefreshLastSelection(emMessages);
    }

    /**
     * 将环信消息转换成数组
     *
     * @param emMessages
     * @return
     */
    private EMMessage[] getEMMessageArray(List<EMMessage> emMessages) {
        EMMessage[] mMessages = emMessages.toArray(new EMMessage[emMessages.size()]);
        return mMessages;
    }

    /**
     * 将myChatMsgs转换成EMMessages
     *
     * @param chatMsgBeanList
     * @return
     */
    private List<EMMessage> getEMMessages(List<ChatMsgBean> chatMsgBeanList) {

        List<EMMessage> emMessages = new ArrayList<>();
        for (int i = 0; i < chatMsgBeanList.size(); i++) {
            //取得消息的发送来源
            ChatMsgBean myMsg = chatMsgBeanList.get(i);
            EMMessage emMessage = createEMMessage(myMsg);
            emMessages.add(emMessage);
        }

        return emMessages;
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    /**
     * 存入数据库
     *
     * @param message               环信消息
     * @param waitUpload            是否需要上传
     * @param onOperationDbCallback
     */
    private void insertOrUpdateDB(EMMessage message, boolean waitUpload, OnOperationDbCallback onOperationDbCallback) {


//        boolean isLogin = getLoginStatus(ChatActivity.this);//没有登录 不用上传
        //TODO 测试用,发布时注掉
         boolean isLogin = true;


        ChatMsgBean myMsg = HxUtils.createMyMsg(message, (isLogin == true ? waitUpload : false));

        insertOrUpdateDB(myMsg, onOperationDbCallback);
    }

    /**
     * 存入消息
     *
     * @param myMsg
     * @param onOperationDbCallback
     */
    private void insertOrUpdateDB(ChatMsgBean myMsg, OnOperationDbCallback onOperationDbCallback) {


        MyLog.d(TAG, "<<<<<<<<<<<<<<<<<<<添加或更新数据库<<<<<<<<<<<<<<<<<<<<<<");

        ChatMsgDaoImpl chatMsgDao = ChatMsgDaoImpl.getIntance(ChatActivity.this);
        //1.判断消息是否存在
        //2.存在则修改
        //3.不存在则添加
        boolean exists = chatMsgDao.isExists(myMsg.getChatid());
        if (!exists) {
            MyLog.d(TAG, "消息不存在,添加---> chatid： " + myMsg.getChatid() + "    消息内容：" + myMsg.getTextmsg());
            //不存在,添加
            chatMsgDao.insert(myMsg);
        } else {
            MyLog.d(TAG, "消息存在,更新      ---> chatid： " + myMsg.getChatid() + "    消息内容：" + myMsg.getTextmsg());
            //存在,更新
            ChatMsgBean oldMsg = chatMsgDao.findByQuery(myMsg.getChatid());
            myMsg.setId(oldMsg.getId());
            chatMsgDao.updata(myMsg);
        }

        if (onOperationDbCallback != null) {
            onOperationDbCallback.onSuccess();
        }
        //TODO 打日志，需删除


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                uploadCacheMsg();

            }
        }, 2000);

    }

    private void insertOrUpdateDB(final List<ChatMsgBean> lists, final OnOperationDbCallback onOperationDbCallback) {
        //1.更新数据库
        new Thread(new Runnable() {
            @Override
            public void run() {
                MyLog.i(TAG, "网络加载数据-----> 存数据库的起始角标：" + tempsize);
                for (int i = tempsize; i < lists.size(); i++) {
                    insertOrUpdateDB(lists.get(i), null);
                }
                if (onOperationDbCallback != null) {
                    onOperationDbCallback.onSuccess();
                }
            }
        }).start();
    }

    public interface OnOperationDbCallback {
        void onSuccess();
    }

    /**
     * 将环信message转成myMessagelist
     *
     * @param message
     * @return
     */
    private List<ChatMsgBean> getChatMsgs(EMMessage message, boolean waitUpload) {
        List<ChatMsgBean> chatMsgBeanList = new ArrayList<>();
        ChatMsgBean myMsg = HxUtils.createMyMsg(message, waitUpload);
        chatMsgBeanList.add(myMsg);
        return chatMsgBeanList;
    }

    /**
     * 将环信message转成myMessagelist
     *
     * @param message
     * @return
     */
    private ChatMsgBean getChatMsg(EMMessage message, boolean waitUpload) {

        ChatMsgBean myMsg = HxUtils.createMyMsg(message, waitUpload);

        return myMsg;
    }

    /**
     * 上传消息到服务器
     *
     * @param myMsg
     * @param url
     */
    private void uploadMsgToApi(ChatMsgBean myMsg, String url, final UploadCacheCallback uploadCacheCallback) {


        if (myMsg == null) {
            if (uploadCacheCallback != null) {
                uploadCacheCallback.onUpload();
            }
            return;
        }
        String jsonStr = getDataJson(myMsg);

        //TODO去服务器
        MyHttp.requestFromJson(this, url, jsonStr, MyHttp.POST, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                MyLog.i(TAG, "上传到zmserver成功，不需要返回数据");

                if (uploadCacheCallback != null) {
                    uploadCacheCallback.onUpload();
                }
            }
            //更新数据的状态

            @Override
            public void onVerifySuccess(String dataRaw) {
                MyLog.d(TAG, "发消息到小i，并上传到zmserver成功，需要返回一条机器人数据内容如下 ：" + dataRaw);
                paseJson(dataRaw);
            }

            @Override
            public void onServerUnKnownError() {
                MyLog.e(TAG, "服务器未知错误");
            }

            @Override
            public void onErrorCodeError(String msg) {

            }
        });
    }

    /**
     * 上传消息到服务器
     *
     * @param chatMsgBeanList
     * @param url
     */
    private void uploadMsgToApi(List<ChatMsgBean> chatMsgBeanList, String url, final UploadCacheCallback uploadCacheCallback) {


        if (chatMsgBeanList == null) {
            if (uploadCacheCallback != null) {
                uploadCacheCallback.onUpload();
            }
            return;
        }
        String jsonStr = getArrayDataJson(chatMsgBeanList);

        //TODO去服务器
        MyHttp.requestFromJson(this, url, jsonStr, MyHttp.POST, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                MyLog.i(TAG, "上传到zmserver成功，不需要返回数据");

                if (uploadCacheCallback != null) {
                    uploadCacheCallback.onUpload();
                }
            }
            //更新数据的状态

            @Override
            public void onVerifySuccess(String dataRaw) {
                MyLog.d(TAG, "发消息到小i，并上传到zmserver成功，需要返回一条机器人数据内容如下 ：" + dataRaw);
                paseJson(dataRaw);
            }

            @Override
            public void onServerUnKnownError() {
                MyLog.e(TAG, "服务器未知错误");
            }

            @Override
            public void onErrorCodeError(String msg) {

            }
        });
    }

    /**
     * 发送消息到小i
     *
     * @param myMsg
     */
    private void sendMsgToXiaoi(ChatMsgBean myMsg) {
        uploadMsgToApi(myMsg, Constant.BASE_URL + Constant.GET_XIAOI_ANSWER, null);
    }

    /**
     * 上传消息到服务器
     *
     * @param chatMsgBeanList
     */
    private void sendMsgToUpLoadMsg(List<ChatMsgBean> chatMsgBeanList, UploadCacheCallback uploadCacheCallback) {
        uploadMsgToApi(chatMsgBeanList, Constant.BASE_URL + Constant.POST_UPDATE_CHAT_MSGS_URL, uploadCacheCallback);
    }

    /**
     * 解析机器人回复的消息
     *
     * @param dataRaw 回复原数据
     */
    private void paseJson(String dataRaw) {
        Gson gson = new Gson();
        //取得机器人消息

        XiaoiMsgBean xiaoiMsg = gson.fromJson(dataRaw, XiaoiMsgBean.class);
        //添加到lists
        ChatMsgBean myMsg = new ChatMsgBean();
        long msgtime = System.currentTimeMillis();
        // TODO
        myMsg.setTextmsg(xiaoiMsg.message);
        myMsg.setChatid(msgtime + "_" + CacheUtils.getLoginUserid(ChatActivity.this) + "");
        myMsg.setMsgtime(msgtime);
        myMsg.setMsgdir(1);
        myMsg.setIsacked(1);
        myMsg.setIsdelivered(1);
        myMsg.setStatus(2);
        myMsg.setIslistened(1);
        myMsg.setMsgtype(1);
        myMsg.setMsgfrom("xiaoi");
        myMsg.setMsgto("user");
        myMsg.setIsonline(ChatMsgBean.ATTR_VALUE_ANDROID);
        myMsg.setUserid(CacheUtils.getLoginUserid(ChatActivity.this));
        myMsg.setNeedUpload(ChatMsgBean.NEED_UPLOAD);
        myMsg.setTypename(MyApp.imei);
        receiveXiaoiNewMsg(myMsg);

    }

    /**
     * 将myChatmessage转换成环信消息
     *
     * @param myMsg
     * @return
     */
    private EMMessage createEMMessage(ChatMsgBean myMsg) {
        //取得消息的发送来源

        int msgdir = myMsg.getMsgdir();
        EMMessage msg = null;
        if (msgdir == ChatMsgBean.FROM) {//1.为接收的消息
//               msg.direct() = EMMessage.Direct.SEND;
            msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            //区分机器人
            if (myMsg.getIsonline() == ChatMsgBean.ATTR_VALUE_ANDROID) {//机器人
//                MyLog.i(TAG, "区分机器人与人工-------> 机器人消息 " + myMsg.getTextmsg());
                msg.setAttribute(ChatMsgBean.ATTR_KEY_RECEIVE, ChatMsgBean.ATTR_VALUE_ANDROID);
            } else {//人工
                msg.setAttribute(ChatMsgBean.ATTR_KEY_RECEIVE, ChatMsgBean.ATTR_VALUE_ONLINE);
//                MyLog.e(TAG, "区分机器人与人工------->  人工消息 " + myMsg.getTextmsg());
            }
        } else { //  发送的消息
            msg = EMMessage.createSendMessage(EMMessage.Type.TXT);

            switch (myMsg.getStatus()) {
                case ChatMsgBean.MSG_STATUS_SEND_SUCCESS:
                    msg.setStatus(EMMessage.Status.SUCCESS);
                    break;
                case ChatMsgBean.MSG_STATUS_SEND_FAIL:
                    msg.setStatus(EMMessage.Status.FAIL);
                    break;
                case ChatMsgBean.MSG_STATUS_SENDING:
                    msg.setStatus(EMMessage.Status.INPROGRESS);
                    break;
            }
            switch (myMsg.getIsonline()) {//设置发送给机器人还是人工在线

                case ChatMsgBean.ATTR_VALUE_ANDROID:
                    msg.setAttribute(ChatMsgBean.ATTR_KEY_SEND_TO, ChatMsgBean.ATTR_VALUE_ANDROID);
                    break;
                case ChatMsgBean.ATTR_VALUE_ONLINE:
                    msg.setAttribute(ChatMsgBean.ATTR_KEY_SEND_TO, ChatMsgBean.ATTR_VALUE_ONLINE);
                    break;
            }
        }
        //设置chatId
        msg.setAttribute(ChatMsgBean.ATTR_KEY_CHATID, myMsg.getChatid());
        //设置消息下面是否带有提示信息（如：人工在线小乐为你服务）
        msg.setAttribute(ChatMsgBean.ATTR_KEY_HINT, myMsg.getShowHint());
        //设置提示的内容
        msg.setAttribute(ChatMsgBean.ATTR_KEY_HINT_TYPE, myMsg.getHintType());

        EMTextMessageBody body = new EMTextMessageBody(myMsg.getTextmsg());
        msg.setMsgTime(myMsg.getMsgtime());
        msg.addBody(body);
        // MyLog.d(TAG,"转成环信消息   消息状态："+msg.status() +"　　　消息内容："+chatMsgBean.getTextmsg());
        return msg;
    }


    /**
     * 将lists生成 JSON 数组
     *
     * @param lists
     * @return
     */
    private String getArrayDataJson(List<ChatMsgBean> lists) {
        Gson gson = new Gson();
        return gson.toJsonTree(lists).toString();

    }

    /**
     * 将chatMsgBean 生成json String
     *
     * @param myMsg
     * @return
     */
    private String getDataJson(ChatMsgBean myMsg) {
        Gson gson = new Gson();
        return gson.toJsonTree(myMsg).toString();
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        uploadCacheMsg();
        Intent intent = new Intent();
        intent.putExtra("isAndroid", isAndroid);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 上传缓存消息
     */
    private void uploadCacheMsg() {

        //1.取得要上传的消息
        final List<ChatMsgBean> upladDB = getUpladDB();

        MyLog.d(TAG, "需要上传的数据条数：" + upladDB.size());
        if (upladDB != null && upladDB.size() > 0) {

            //2.批量上传
            sendMsgToUpLoadMsg(upladDB, new UploadCacheCallback() {
                @Override
                public void onUpload() {

                    for (ChatMsgBean chatMsgBean : upladDB) {
                        chatMsgBean.setNeedUpload(ChatMsgBean.DO_NOT_NPLOAD);
                        insertOrUpdateDB(chatMsgBean, null);
                    }
                }
            });
        } else {

        }


    }

    public interface UploadCacheCallback {
        void onUpload();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApp.IS_CHAT_PROGUND = false;

    }

    private View.OnTouchListener touchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    // 1.开启语音识别
                    mIat = MscUtils.getInstance().startMsc(getApplicationContext());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MscUtils.setParam(mIat);
                    MscUtils.getInstance().startListening(mIat, resustCallback);
                    mVoiceHintWindow.setVisibility(View.VISIBLE);
                    mVolume.setImageResource(R.drawable.ic_volume_01);
                    // 2. 显示音量
                    // 3. 在音量回调中更新音量大小
                    break;
                case MotionEvent.ACTION_UP:
                    //
                    // 1.关闭语音识别
                    mVoiceHintWindow.setVisibility(View.INVISIBLE);

                    // 2.关闭音量显示
                    break;

                default:
                    break;
            }
            return true;
        }
    };

    /**
     * 语音识别的回调接口
     */
    private MscUtils.onResustCallback resustCallback = new MscUtils.onResustCallback() {
        @Override
        public void onVolumeChanged(int volume) {
            // 发消息改音量图片
            Message msg = Message.obtain();
            msg.what = CHANGE_VOLUME;
            msg.obj = volume;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onResult(String result) {
            //取得了识别的内容
            mIat = MscUtils.getInstance().startMsc(getApplicationContext());
            mIat.cancel();
            Message msg = Message.obtain();
            msg.what = SET_CONTECT;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onError(int error) {

        }
    };

    /**
     * 记录重复消息数量
     */
    public class MsgCount {
        private int count;
        private String lastmsg;
        private boolean isSwitch = false;

        public boolean addMsg(String msg, boolean isAndroid) {
            //判断是否与上一次消息相同
            if (isAndroid) {
                MyLog.i(TAG, "本是发给机器人, 不操作");
                count = 0;
                isSwitch = false;
            } else {
                if (!Tools.isEmpty(lastmsg)) {
                    if (msg.equals(lastmsg)) {//消息相同增加count
                        count++;
                        MyLog.e(TAG, "消息与上一次消息相同 lastmsg: " + lastmsg + "inputmsg: " + msg + "  计数： " + count);
                        lastmsg = msg;
                    } else {//不同清除count
                        count = 0;
                        MyLog.d(TAG, "------消息与上一次消息不同 lastmsg: " + lastmsg + "inputmsg: " + msg + "  计数： " + count);
                        lastmsg = msg;
                    }
                    if (count > 2) {//已切换到机器人清除count
                        isSwitch = true;
                        count = 0;
                        MyLog.e(TAG, "已有三次相同，返回 true     count: " + count);
                    } else {
                        MyLog.e(TAG, "没达到三次相同，返回 false     count: " + count);
                        isSwitch = false;
                    }
                } else {
                    lastmsg = msg;
                }
            }
            return isSwitch;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("isAndroid", isAndroid);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_out_to_bottom);
    }
}